<template>
  <div>
    <!--头部组件-->
    <el-divider content-position="left">
      操作
    </el-divider>
    <el-button type="primary" plain
               @click="mdTemplateImport.templateImportDialog=!mdTemplateImport.templateImportDialog">从Md文件导入
    </el-button>
    <!--md文件导入对话框-->
    <el-dialog
        title="模板导入"
        :visible.sync="mdTemplateImport.templateImportDialog"
        center
        @close="handleClose"
        :before-close="handleBeforeClose"
        :close-on-click-modal="!importing"
        :close-on-press-escape="!importing"
        :show-close="!importing"
        width="90%">
      <el-backtop target=".el-dialog__wrapper"></el-backtop>
      <el-steps :active="mdTemplateImport.currentStep" finish-status="success" simple style="margin-top: 20px">
        <el-step title="导入文件"></el-step>
        <el-step title="预览效果"></el-step>
        <el-step title="确认导入"></el-step>
      </el-steps>
      <!--第一步-->
      <el-row type="flex" justify="center" align="center">
        <el-col :span="0.1">
          <div v-show="mdTemplateImport.currentStep===0">
            <el-upload
                style="padding: 30px 0;text-align: center"
                ref="mdFileImport"
                action=""
                :on-remove="handleImportRemove"
                :before-remove="beforeImportRemove"
                :on-change="handleImportChange"
                multiple
                :on-exceed="handleImportExceed"
                :file-list="mdTemplateImport.fileImportList"
                accept=".md"
                :auto-upload="false">
              <el-button type="primary">开始导入</el-button>
              <div slot="tip" class="el-upload__tip">只支持上传md文件</div>
            </el-upload>
            <el-row type="flex" justify="center" align="center">
              <el-col :span="0.1">
                <el-button plain @click="drawingHtml">下一步</el-button>
              </el-col>
            </el-row>
          </div>
          <!--第二步-->
          <el-row type="flex" justify="center" align="center"
                  class="stepBox"
                  v-show="mdTemplateImport.currentStep===1" v-loading="mdTemplateImport.loadStatus"
                  element-loading-text="文件正在渲染中">
            <el-col :span="20">
              <!--回顶-->
              <le-preview ref="mdTemplateImportPreviewRef" :is-md="true" :value="mdTemplateImport.mdContent"
                          :hljs-css="mdTemplateImport.hljsCss"></le-preview>
              <el-pagination
                  v-show="!mdTemplateImport.loadStatus"
                  style="text-align: center;padding: 30px 0"
                  layout="prev, pager, next"
                  :page-count="mdTemplateImport.mdFileList.length"
                  :current-page.sync="mdTemplateImport.currentPage"
                  @current-change="mdTemplateImport.mdContent = mdTemplateImport.mdFileList[mdTemplateImport.currentPage - 1].emailContent"
                  background>
              </el-pagination>
            </el-col>
          </el-row>
          <el-row :gutter="20" type="flex" justify="center" align="center" v-show="mdTemplateImport.currentStep===1">
            <el-col :span="0.1">
              <el-button plain @click="mdTemplateImport.currentStep--">上一步</el-button>
            </el-col>
            <el-col :span="0.1">
              <el-button plain @click="initialHtmlTemplate">下一步</el-button>
            </el-col>
          </el-row>
          <!--第三步-->
          <el-row :gutter="20" type="flex" justify="center" align="center" v-show="mdTemplateImport.currentStep===2"
                  class="stepBox">
            <el-col :span="20">
              <el-descriptions title="模板数据导入信息表" direction="vertical" :column="3" border>
                <el-descriptions-item label="文件个数">
                  {{ mdTemplateImport.htmlFormatList.length }}
                </el-descriptions-item>
                <el-descriptions-item label="源文件格式">
                  <el-tag size="small">*.md</el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="转换状态">
                  <el-tag size="small">已转换为html</el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="导入进度">
                  <el-progress :percentage="mdTemplateImport.importProgress.importPercent"></el-progress>
                </el-descriptions-item>
              </el-descriptions>
            </el-col>
          </el-row>
          <el-row :gutter="20" type="flex" justify="center" align="center" v-show="mdTemplateImport.currentStep===2">
            <el-col :span="0.1">
              <el-button plain @click="mdTemplateImport.currentStep--" :disabled="importing">上一步</el-button>
            </el-col>
            <el-col :span="0.1">
              <el-button type="primary" @click="sureImport" :disabled="importing">确认导入
              </el-button>
            </el-col>
          </el-row>
          <!--第三步结束-->
          <el-row :gutter="20" type="flex" justify="center" align="center" v-show="mdTemplateImport.currentStep===3"
                  class="stepBox">
            <el-col :span="22">
              <el-result icon="success" title="导入成功" subTitle="模板已成功导入,可在发送新邮件时使用">
                <template slot="extra">
                  <el-descriptions direction="vertical" :column="1" border>
                    <el-descriptions-item label="成功">{{ mdTemplateImport.importProgress.success }}
                    </el-descriptions-item>
                    <el-descriptions-item label="失败">{{ mdTemplateImport.importProgress.failedList.length }}
                    </el-descriptions-item>
                    <el-descriptions-item label="总数">{{ mdTemplateImport.importProgress.total }}</el-descriptions-item>
                    <el-descriptions-item label="失败详细" v-if="mdTemplateImport.importProgress.failedList.length>0">
                      <el-table
                          :data="mdTemplateImport.importProgress.failedList"
                          height="250"
                          border
                          style="width: 100%">
                        <el-table-column
                            prop="emailTitle"
                            label="模板标题">
                        </el-table-column>
                        <el-table-column
                            prop="because"
                            label="原因">
                        </el-table-column>
                      </el-table>
                    </el-descriptions-item>
                  </el-descriptions>
                  <el-row :gutter="10" type="flex" justify="center" align="center" style="padding: 30px 0">
                    <el-col :span="0.1">
                      <el-button plain size="medium" @click="mdTemplateImport.templateImportDialog=false">关闭
                      </el-button>
                    </el-col>
                  </el-row>
                </template>
              </el-result>
            </el-col>
          </el-row>
        </el-col>
      </el-row>
    </el-dialog>
    <h3>模板数据表</h3>
    <el-row>
      <el-col :xs="24" :sm="24" :md="18" :lg="18" :xl="18">
        <el-table
            :data="templates"
            border
            stripe>
          <el-table-column
              prop="emailTitle"
              label="标题">
          </el-table-column>
          <el-table-column
              fixed="right"
              label="操作"
              width="200">
            <template slot-scope="scope">
              <el-link
                  :underline="false"
                  icon="el-icon-view"
                  @click="handlePreview(scope.$index, scope.row)">预览
              </el-link>
              <el-divider direction="vertical"></el-divider>
              <el-button
                  size="mini"
                  type="danger"
                  @click="handleDelete(scope.$index, scope.row)">删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>
    <!--模板预览对话框-->
    <el-dialog
        title="模板预览"
        :visible.sync="templatePreview.templatePreviewDialogVisible"
        width="60%"
        @close="clearPreviewInfo"
        center>
      <le-preview ref="html-preview" :value="templatePreview.templateHtml"
                  :hljs-css="templatePreview.hljsCss"></le-preview>
    </el-dialog>
  </div>
</template>

<script>
import {Message} from "element-ui";

export default {
  name: "MailTemplate",
  data() {
    return {
      templates: [],
      templateKeyWord: '',
      //模板预览
      templatePreview: {
        templatePreviewDialogVisible: false,
        //markdown配置属性
        hljsCss: 'agate',
        templateHtml: ''
      },
      //模板编辑
      templateEdit: {
        templateEditDialogVisible: false,
        hljsCss: 'agate',
        templateMdVal: ''
      },
      //md模板导入对话框
      mdTemplateImport: {
        templateImportDialog: false,
        //md模板导入集合
        fileImportList: [],
        //当前步骤
        currentStep: 0,
        loadStatus: false,
        //从导入的md集合中读取到的数据
        mdFileList: [],
        //预览组件配置
        hljsCss: 'agate',
        mdContent: '',
        currentPage: 0,
        htmlFormatList: [],
        importProgress: {
          success: 0,
          total: 0,
          importPercent: 0,
          failedList: []
        },
      },
      //当前导入的下标
      currentIndex: 0,
      //导入状态
      importing: false
    }
  }, mounted() {
    this.getTemplates();
  }, methods: {
    async getTemplates() {
      let rs = await this.axios.get('emailcontent/getEmailTemplate');
      this.templates = rs.data.content.templateOptions;
    }, async handlePreview(index, row) {
      let rs = await this.getTemplate(row.id);
      this.templatePreview.templateHtml = rs.emailContent;
      this.templatePreview.templatePreviewDialogVisible = true;
    }, async handleEdit(index, row) {
      let rs = await this.getTemplate(row.id);
      this.templateEdit.templateMdVal = this.turnDownService.turndown(rs.emailContent);
      this.templateEdit.templateEditDialogVisible = true;
    },
    handleDelete(index, row) {
      this.$confirm('此操作将永久删除该模板, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        let rs = await this.axios.delete(`emailcontent/delete?id=${row.id}`);
        if (rs.data.code === 200) {
          Message.success('删除成功');
          await this.getTemplates();
        } else {
          Message.error('删除失败');
        }
      }).catch(() => {
        Message.info('已取消删除');
      });
    },
    //根据模板的ID向后端获取该模板的相关信息
    async getTemplate(id) {
      return (await this.axios.get(`emailcontent/getEmailTemplate?id=${id}`)).data.content.templateOptions[0];
    },
    //关闭后清理对话框中遗留的数据
    clearEditInfo() {
      this.templateEdit.templateMdVal = '';
    },
    save(val) {
      console.log(val);
    },
    clearPreviewInfo() {
      this.templatePreview.templateHtml = '';
    },
    //从md文件转换导入模板操作
    //当确认删除文件后
    handleImportRemove(file) {
      //定位文件的索引
      this.mdTemplateImport.fileImportList.splice(this.mdTemplateImport.fileImportList.indexOf(file), 1);
    },
    handleImportExceed(files, fileList) {
      this.$message.warning(`当前限制选择 5 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    beforeImportRemove(file) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    handleImportChange() {
      this.mdTemplateImport.fileImportList = this.$refs.mdFileImport._data.uploadFiles;
    },
    //关闭前先提示确认
    handleBeforeClose(done) {
      this.$confirm('确认关闭吗？')
          .then(_ => {
            //如果当前是正在导入,则不能进行关闭
            if (this.mdTemplateImport.importProgress.total !== 0 && this.mdTemplateImport.importProgress.importPercent !== 100)
              return Message.warning('当前正在导入,无法关闭,请在导入完成后关闭!');
            done();
          })
          .catch(_ => {
          });
    },
    //模态框关闭前先清理导入的数据
    handleClose() {
      //清空已上传的文件列表
      this.$refs.mdFileImport.clearFiles();
      //重置导入对象的一些信息
      this.mdTemplateImport.fileImportList = [];
      this.mdTemplateImport.currentStep = 0;
      this.mdTemplateImport.loadStatus = false;
      this.mdTemplateImport.mdFileList = [];
      this.mdTemplateImport.mdContent = '';
      this.mdTemplateImport.currentPage = 1;
      this.mdTemplateImport.htmlFormatList = [];
      this.mdTemplateImport.importProgress = {
        success: 0,
        total: 0,
        importPercent: 0,
        failedList: []
      };
    },
    //渲染预览效果
    drawingHtml() {
      //判断集合长度是否有md文件
      if (!this.mdTemplateImport.fileImportList.length > 0)
        return Message.warning("至少导入一个文件");
      this.mdTemplateImport.currentStep++;
      this.mdTemplateImport.loadStatus = true;
      //先清空md数据集合,否则数据有误
      this.mdTemplateImport.mdFileList = [];
      //清空预览数据
      this.mdTemplateImport.mdContent = '';
      //前端fori效率高,所以采用fori
      for (let i = 0; i < this.mdTemplateImport.fileImportList.length; i++) {
        let fileReader = new FileReader();
        fileReader.readAsText(this.mdTemplateImport.fileImportList[i].raw, 'utf-8');
        fileReader.onload = () => {
          //读取后并追加到md数据集合中
          let name = this.mdTemplateImport.fileImportList[i].name;
          this.mdTemplateImport.mdFileList.push({
            emailTitle: name.substr(0, name.indexOf('.')),
            emailContent: fileReader.result
          });
        }
      }
      setTimeout(() => {
        //等待刷新 否则数据无法获得
        this.mdTemplateImport.mdContent = this.mdTemplateImport.mdFileList[this.mdTemplateImport.currentPage - 1].emailContent;
        this.mdTemplateImport.loadStatus = false;
      }, 1000);
    },
    /*
    * 进入确认导入前,先将预览渲染的数据转化为html的格式放入数组
    * */
    initialHtmlTemplate() {
      //清空数组
      this.mdTemplateImport.htmlFormatList = [];
      for (let i = 0; i < this.mdTemplateImport.mdFileList.length; i++) {
        this.mdTemplateImport.htmlFormatList.push({
              emailTitle: this.mdTemplateImport.mdFileList[i].emailTitle,
              emailContent: this.mdConverter.makeHtml(this.mdTemplateImport.mdFileList[i].emailContent)
            }
        );
      }
      //赋予总数
      this.mdTemplateImport.importProgress.total = this.mdTemplateImport.htmlFormatList.length;
      this.mdTemplateImport.currentStep++;
    }, sureImport() {
      this.importing = true;
      if (this.currentIndex < this.mdTemplateImport.htmlFormatList.length) {
        /*
        * 捕获异常,如果出现异常则将出现错误的模板放入失败集合中
        * */
        //每一次请求前先审核内容,如果通过则导入,不通过则放入失败数组中
        let htmlFormatListElement = this.mdTemplateImport.htmlFormatList[this.currentIndex];
        this.axios.get(`emailcontent/checkEmailContent`, {
          params: {
            content: htmlFormatListElement.emailContent
          },
          timeout: 10000
        }).then((checkRs) => {
          console.log(checkRs['error_code']);
          let resData = checkRs.data;
          // 审核结果类型，可取值1、2、3、4，分别代表1：合规，2：不合规，3：疑似，4：审核失败
          if (resData.conclusionType === 1) {
            this.axios.post('emailcontent/insertEmailTemplate', htmlFormatListElement).then((rs) => {
              if (rs.data.content.success === 200) {
                this.mdTemplateImport.importProgress.success++;
              }
            }).catch((err) => {
              //出现异常后
              let tempTmp = {
                emailTitle: this.mdTemplateImport.mdFileList[this.currentIndex].emailTitle,
                content: this.mdTemplateImport.htmlFormatList[this.currentIndex],
                because: err
              };
              this.mdTemplateImport.importProgress.failedList.push(tempTmp);
            }).finally(() => {
              //每一次最后一步操作 计算百分比  当前进度条百分比=Number((成功数量+失败数量)/总数量)
              this.mdTemplateImport.importProgress.importPercent = Number(((this.mdTemplateImport.importProgress.success + this.mdTemplateImport.importProgress.failedList.length) / this.mdTemplateImport.importProgress.total * 100).toFixed(2));
              this.currentIndex++;
              this.sureImport();
            });
          } else if (resData.conclusionType === 2) {
            let tempWord = '';
            for (let i = 0; i < resData.data.length; i++) {
              tempWord += ',' + resData.data[i].msg;
            }
            throw new Error(tempWord);
          } else if (resData.conclusionType === 3) {
            throw new Error(`${this.mdTemplateImport.mdFileList[this.currentIndex].emailTitle}内容疑似不合规`);
          } else if (resData.conclusionType === 4) {
            throw new Error(`${this.mdTemplateImport.mdFileList[this.currentIndex].emailTitle}审核失败`);
          }
        }).catch((err) => {
          //出现异常后
          let tempTmp = {
            emailTitle: this.mdTemplateImport.mdFileList[this.currentIndex].emailTitle,
            content: this.mdTemplateImport.htmlFormatList[this.currentIndex],
            because: err.toString()
          };
          this.mdTemplateImport.importProgress.failedList.push(tempTmp);
          this.mdTemplateImport.importProgress.importPercent = Number(((this.mdTemplateImport.importProgress.success + this.mdTemplateImport.importProgress.failedList.length) / this.mdTemplateImport.importProgress.total * 100).toFixed(2));
          this.currentIndex++;
          this.sureImport();
        })
      } else {
        //导入结束
        this.mdTemplateImport.currentStep++;
        this.importing = false;
        this.currentIndex = 0;
        this.getTemplates();
      }
    }
  }
}
</script>

<style scoped>
.stepBox {
  padding: 30px 0;
  min-height: 300px;
  margin: 10px 0;
}
</style>